package com.mediacloud.app.newsmodule.fragment.video.vod;

import android.graphics.Rect;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.constraintlayout.widget.ConstraintLayout;

import com.chinamcloud.report.ReportKit;
import com.eventTrack.CDPTrackReportManager;
import com.eventTrack.TXReportManager;
import com.mediacloud.app.assembly.util.StringUtils;
import com.mediacloud.app.assembly.util.Utility;
import com.mediacloud.app.model.component.ComponentItem;
import com.mediacloud.app.model.eventbus.event.LoginEvent;
import com.mediacloud.app.model.fragment.BaseFragment;
import com.mediacloud.app.model.news.ArticleItem;
import com.mediacloud.app.model.news.CatalogItem;
import com.mediacloud.app.model.news.ProgramListItem;
import com.mediacloud.app.model.news.ShowSwitch;
import com.mediacloud.app.newsmodule.R;
import com.mediacloud.app.newsmodule.activity.InteractVideoDetailActivity;
import com.mediacloud.app.newsmodule.activity.VideoLiveVRDetailActivity;
import com.mediacloud.app.newsmodule.activity.VideoVodDetailActivity;
import com.mediacloud.app.newsmodule.activity.VideoVodVRDetailActivity;
import com.mediacloud.app.newsmodule.adaptor.component.IExposure;
import com.mediacloud.app.newsmodule.fragment.imagetext.RelatedType;
import com.mediacloud.app.newsmodule.fragment.recommend.ComponentLiveListFragment;
import com.mediacloud.app.newsmodule.model.AddHistoryParamsData;
import com.mediacloud.app.newsmodule.newsdetail_component.NewsDetailComponentUtils;
import com.mediacloud.app.newsmodule.utils.AppfacBuyEnableUtils;
import com.mediacloud.app.newsmodule.utils.CollectionController;
import com.mediacloud.app.newsmodule.utils.HistoryInvoker;
import com.mediacloud.app.newsmodule.utils.LoginUtils;
import com.mediacloud.app.newsmodule.utils.RelativeNewsInvoker;
import com.mediacloud.app.newsmodule.utils.ShareGridClickUtil;
import com.mediacloud.app.newsmodule.view.BaseSpiderView;
import com.mediacloud.app.newsmodule.view.ShareComponent;
import com.mediacloud.app.reslib.enums.AppFactoryGlobalConfig;
import com.mediacloud.app.share.model.ShareGridItem;
import com.mediacloud.app.user.model.UserInfo;
import com.mediacloud.app.util.TimeUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 基于评论的点播
 */
public class VideoVodDetailFragment extends BaseFragment implements ComponentLiveListFragment.GetProgramData {
    protected TextView videoTitle, originalLabel;
    protected TextView tvSource, tvSummary, tvPlayCount, tvPublishData, tvAuthor;
    protected ImageView arrowIco;

    LinearLayout LinearLayoutContainer;
    ScrollView headerScroller;

    CatalogItem catalogItem;
    RelativeNewsInvoker relativeNewsInvoker;
    View introduceViewHeader;
    TextView videoIntroduce;
    private ArticleItem articleItem;
    ArrayList<ComponentItem> components;

    BaseSpiderView spiderView;

    ShowSwitch showSwitch;
    boolean appfacBuy;


    public ArticleItem getArticleItem() {
        return articleItem;
    }

    public void setArticleItem(ArticleItem articleItem) {

        this.articleItem = articleItem;
        if(!TextUtils.isEmpty(articleItem.getSummary())){
            tvSummary.setText(articleItem.getSummary());
        }
        if(!TextUtils.isEmpty(articleItem.getTitle())){
            videoTitle.setText(articleItem.getTitle());
        }
        if(!TextUtils.isEmpty(articleItem.getReferName())){
            tvSource.setText(articleItem.getReferName());
        }
        tvSource.setVisibility(View.GONE);
        if(!TextUtils.isEmpty(articleItem.getPublishdate_format())){
            tvPublishData.setText(articleItem.getPublishdate_format());
        }

        if (TextUtils.isEmpty(articleItem.getPublishdate_format())) {
            tvPublishData.setVisibility(View.GONE);
        } else {
            tvPublishData.setVisibility(View.VISIBLE);
        }
        if (articleItem.getExtension() != null && articleItem.getExtension().getOriginalFlag() == 0) {
            originalLabel.setVisibility(View.GONE);
        } else {
            originalLabel.setVisibility(View.VISIBLE);
        }
    }


    @Override
    protected void initArgs() {
        super.initArgs();
        components = getArguments().getParcelableArrayList("components");
        appfacBuy = getArguments().getBoolean("appfacBuy");
    }

    @Override
    public void initView() {
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        LinearLayoutContainer = Utility.findViewById(mRootView, R.id.LinearLayoutContainer);
        headerScroller = Utility.findViewById(mRootView, R.id.headerScroller);
        headerScroller.setOnScrollChangeListener(new View.OnScrollChangeListener() {
            @Override
            public void onScrollChange(View v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
                runTask();
            }
        });
        articleItem = getFragmentArguments().getParcelable("data");
        catalogItem = getFragmentArguments().getParcelable("catalog");
        if (articleItem != null) {
            showSwitch = articleItem.getmShowSwitch();
        }
        initVideoInfoHeader();

        if (components != null && components.size() > 0) {
            articleItem.mShowSwitch = showSwitch;
//            DCPTManager.INSTANCE.addComponent(LinearLayoutContainer, null,components, articleItem, getChildFragmentManager(), 1, this);
            ArrayList<ComponentItem> summaryComponent = new ArrayList<>();
            for (int i = 0; i < components.size(); i++) {
                if (components.get(i).getWidget() == RelatedType.VIDEO_RICH_SUMMARY){
                     summaryComponent.add(components.remove(i));
                }
            }
            if (summaryComponent.size() > 0)
                NewsDetailComponentUtils.addComponentList(LinearLayoutContainer,summaryComponent,articleItem, getActivity(), getChildFragmentManager(), 1, this);
            if (articleItem.getExtension()!=null && articleItem.getExtension().getRelaSpecial() != null){
                if (!TextUtils.isEmpty(articleItem.getExtension().getRelaSpecial()) && !articleItem.getExtension().getRelaSpecial().equals("{}")){
                    NewsDetailComponentUtils.addTopicComponent(
                            LinearLayoutContainer,
                            getActivity(),articleItem.getExtension().getRelaSpecial(),
                            this);
                }
            }
            NewsDetailComponentUtils.addComponentList(LinearLayoutContainer, components, articleItem, getActivity(), getChildFragmentManager(), 1, this);
            runTask();
        }
        if (getActivity() instanceof VideoVodDetailActivity) {
            ((VideoVodDetailActivity) getActivity()).hiddBroccoliLayout();
            // ((VideoVodDetailActivity) getActivity()).mBaiduPlayer.setExtDateSuccess();
        }
        if (getActivity() instanceof VideoVodVRDetailActivity) {
            ((VideoVodVRDetailActivity) getActivity()).hiddBroccoliLayout();
        }
        if (getActivity() instanceof VideoLiveVRDetailActivity) {
            ((VideoLiveVRDetailActivity) getActivity()).hiddBroccoliLayout();
        }
        if (getActivity() instanceof InteractVideoDetailActivity) {
            ((InteractVideoDetailActivity) getActivity()).hiddBroccoliLayout();
        }
    }

    protected void initVideoInfoHeader() {
        View view = LayoutInflater.from(getActivity()).inflate(R.layout.aappfactory_voddetail_header_videoinfo, null);
        view.setFocusable(true);
        view.setFocusableInTouchMode(true);
        view.requestFocus();
        LinearLayoutContainer.addView(view);
        spiderView = view.findViewById(R.id.spiderView);

        videoTitle = Utility.findViewById(view, R.id.tvTitle);
        tvSource = Utility.findViewById(view, R.id.tvSource);
        tvAuthor = Utility.findViewById(view, R.id.tvAuthor);
        originalLabel = Utility.findViewById(view, R.id.originalLabel);
        tvPlayCount = Utility.findViewById(view, R.id.tvPlayCount);
        tvSummary = Utility.findViewById(view, R.id.tvSummary);
        tvPublishData = Utility.findViewById(view, R.id.tvPublishData);
        arrowIco = Utility.findViewById(view, R.id.arrowIco);
        arrowIco.setOnClickListener(v -> {
            if (arrowIco.isSelected()) {
                tvSummary.setVisibility(View.GONE);
                arrowIco.animate().rotationBy(-180).start();
            } else {
                tvSummary.setVisibility(View.VISIBLE);
                arrowIco.animate().rotationBy(180).start();
            }
            arrowIco.setSelected(!arrowIco.isSelected());
        });


        // boolean openDownloadBtn = AppFactoryGlobalConfig.getAppServerConfigInfo(getActivity()).getOtherFunction() != null && AppFactoryGlobalConfig.getAppServerConfigInfo(getActivity()).getOtherFunction().getDownload() > 0;// "1".equals(getActivity().getResources().getString(R.string.openDownloadBtn));
        if (!TextUtils.isEmpty(articleItem.getReal_title())) {
            videoTitle.setText(articleItem.getReal_title());
        } else {
            videoTitle.setText(articleItem.getTitle());
        }

        if (TextUtils.isEmpty(articleItem.getAuthor())) {
            tvAuthor.setVisibility(View.GONE);
        } else {
            tvAuthor.setVisibility(View.GONE);
            tvAuthor.setText(articleItem.getAuthor());
        }

        tvPublishData.setText(TimeUtils.originalTimeToEndDay(articleItem.getPublishdate()));
        tvSummary.setText(articleItem.getSummary());

        if (articleItem.getSpider() != null) {
            spiderView.setDate(articleItem);
        }

        if (TextUtils.isEmpty(articleItem.getReferName())) {
            tvSource.setText(getResources().getString(R.string.app_name));
        } else {
            tvSource.setText(articleItem.getReferName());
        }
        if (TextUtils.isEmpty(articleItem.getPublishdate_format())) {
            tvPublishData.setVisibility(View.GONE);
        } else {
            tvPublishData.setVisibility(View.VISIBLE);
        }
        if (articleItem.getExtension()!= null && articleItem.getExtension().getOriginalFlag() == 0){
            originalLabel.setVisibility(View.GONE);
        }else{
            originalLabel.setVisibility(View.VISIBLE);
        }
//        ConstraintLayout.LayoutParams layoutParams = (ConstraintLayout.LayoutParams) tvPublishData.getLayoutParams();
//        if (tvAuthor.getVisibility() == View.VISIBLE) {
//            layoutParams.topToBottom = R.id.tvAuthor;
//        } else if (tvSource.getVisibility() == View.VISIBLE) {
//            layoutParams.topToBottom = R.id.tvSource;
//        }
//        tvPublishData.setLayoutParams(layoutParams);
        handler.sendEmptyMessageDelayed(0, 1000);
    }


    private Handler handler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            addHistory();
        }
    };
    private HistoryInvoker HistoryInvoker;

    private void addHistory() {
        HistoryInvoker = new HistoryInvoker();
        AddHistoryParamsData paramsData = new AddHistoryParamsData();
        paramsData.source = CollectionController.convertToSource(catalogItem);
        if (articleItem.getId() > 0) {
            paramsData.source_id = articleItem.getId();
        } else {
            if (!TextUtils.isEmpty(articleItem.getReferTarget())) {
                try {
                    paramsData.source_id = Long.parseLong(articleItem.getReferTarget());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

        paramsData.summary = articleItem.getSummary();
        paramsData.title = articleItem.getTitle();
        paramsData.type = articleItem.getType() + "";
        paramsData.url = articleItem.getUrl();
        paramsData.logo = articleItem.getLogo();
        paramsData.publishdate_format = articleItem.getPublishdate_format();
        paramsData.isFromEpaper = articleItem.isEPaper ? "1" : "0";
        paramsData.logoImgSize = articleItem.getLogoImgSize();
        HistoryInvoker.addHistory(UserInfo.getUserInfo(getContext()).getUserid(), paramsData, null);
    }

    protected void updateVideoIntroduce(String introduce) {
        videoIntroduce.setText(introduce);
        if (TextUtils.isEmpty(introduce)) {
            introduceViewHeader.setVisibility(View.GONE);
        } else {
            introduceViewHeader.setVisibility(View.VISIBLE);
        }
    }


    protected void intoLogin() {
//        ToastUtil.show(getActivity(), R.string.please_login);
        LoginUtils.request_source = "视频播放配置";
        LoginUtils.invokeLogin(getActivity());
    }

    public int getLayoutResID() {
        return R.layout.aappfactory_fragment_videovod;
    }


    @Override
    public void onDestroyView() {
        if (LinearLayoutContainer!=null)
        LinearLayoutContainer.removeCallbacks(exposureTask);

        spiderView.destroy();
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
        if (handler != null) {
            handler.removeCallbacksAndMessages(this);
            handler = null;
        }
        if (relativeNewsInvoker != null) relativeNewsInvoker.destory();
        super.onDestroyView();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        AppfacBuyEnableUtils.refresh(getActivity(), appfacBuy);
    }


    @Override
    public void getProgram(List<Map<String, List<ProgramListItem>>> data) {
    }


    @Override
    public void onSaveInstanceState(Bundle outState) {
        outState.putParcelable("data", articleItem);
        outState.putParcelable("catalog", catalogItem);
        super.onSaveInstanceState(outState);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void userLoginEvent(LoginEvent loginEvent) {
        if (UserInfo.getUserInfo(requireActivity()).isLogin()) {
            spiderView.checkIsAttention();
        }
    }

    @ShareComponent.AdapterViewItemClicked
    public void onItemClick(AdapterView<?> parent, View view, int position, long id, ShareGridItem item) {
        Log.i(TAG, "@ShareComponent.AdapterViewItemClicked onItemClick" + parent + "view " + view + "position " + position + "id " + id);
        ShareGridClickUtil.ShareGridClickHandle(item.label, articleItem, catalogItem, getActivity());
    }

    public void setVideoReades(int reades) {

        if (tvPlayCount != null) {
            tvPlayCount.setText("全网传播量"+ StringUtils.toTenThousand((long) reades));
        }

    }

    //    if (videoVodDetailActivity != null && videoVodDetailActivity.mBaiduPlayer != null) {
//        videoVodDetailActivity.mBaiduPlayer.setCollectionchecked(isCollection);
//    }
    public void runTask() {
        if (LinearLayoutContainer != null) {
            LinearLayoutContainer.removeCallbacks(exposureTask);
            LinearLayoutContainer.postDelayed(exposureTask, TXReportManager.EXPOSURE_DELAY);
        }
    }

    public Runnable exposureTask = new Runnable() {
        @Override
        public void run() {
            if (LinearLayoutContainer != null) {
                if (LinearLayoutContainer.getGlobalVisibleRect(new Rect())) {
                    for (int i = 0; i < LinearLayoutContainer.getChildCount(); i++) {
                        View childView = LinearLayoutContainer.getChildAt(i);
                        if (childView.getGlobalVisibleRect(new Rect())) {
                            if (childView instanceof IExposure) {
                                ArrayList<ArticleItem> articleItems = (ArrayList<ArticleItem>) ((IExposure) childView).getExposureArticles();
                                if (articleItems != null && !articleItems.isEmpty()) {
                                    for (ArticleItem item : articleItems) {
                                        TXReportManager.getInstance().app_jhapp_content_detail_rec_imp(item);
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    };
}